package cn.tedu.egmvc4.base.exception;

import cn.tedu.egmvc4.base.response.JsonResult;
import cn.tedu.egmvc4.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice

public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult doHandlerIllegalArgumentException(IllegalArgumentException ex){
        String data = ex.getMessage();
        log.error("参数非法异常：{}",ex.getMessage());
        return new JsonResult(StatusCode.OPERATION_FAILED,data);
    }

    @ExceptionHandler
    public JsonResult doHandlerMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.debug("MethodArgumentNotValidException:{}",data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }


    @ExceptionHandler
    public JsonResult doHandlerConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getMessage().split(":")[1].trim();
        log.debug("ConstraintViolationException:{}",data);
        return new JsonResult(StatusCode.OPERATION_FAILED,data);
    }

    @ExceptionHandler
    public JsonResult doHandlerRuntimeException(RuntimeException ex){
        String data = ex.getMessage();
        log.debug("RuntimeException:{}",ex.getMessage());
        return new JsonResult(StatusCode.OPERATION_FAILED,data);
    }

    @ExceptionHandler
    public JsonResult doHandlerThrowable(Throwable ex){
        String data = ex.getMessage();
        log.debug("Throwable:{}",ex.getMessage());
        return new JsonResult(StatusCode.THROWABLE_ERROR,data);
    }

}
